from flask import Flask, jsonify, request
import os, random
import numpy as np
import pandas as pd
import base64

import logging.config
import logging
import config

import sys
sys.path.append('../../model')
sys.path.append('../../recommand')
from style_transfer import StyleTransfer
from recom import Recom


recommand_clicks = np.array(pd.read_csv('recommand_clicks.csv', sep=',', header=None))
recommand_style_root = './styles'
recommander = Recom()
transfer = StyleTransfer()

app = Flask(__name__)
app.config.from_object(config)
logging.config.fileConfig('logging.conf')


rootLogger =logging.getLogger()
rootLogger.debug("This is root Logger,debug")

rootLogger.debug("This is applog ,debug")

@app.route('/')
def hello_world():  # put application's code here
    return 'Hello World!'


@app.route('/recommendation', methods=["POST"])
def recommendation():
    json_data = request.json
    photo = json_data["user_photo"]
    label = recommander.get_class(photo)
    clicks = recommand_clicks[:, label]
    possbilities = clicks / np.sum(clicks)
    recom_style_names = np.random.choice(config.STYLE_NAMES, 5, p=possbilities)
    photos = []
    for s_name in recom_style_names:
        s_dir = os.path.join(recommand_style_root, s_name)
        s_list = os.listdir(s_dir)
        random.shuffle(s_list)
        s_path = os.path.join(s_dir, s_list[0])
        rf = open(s_path, 'rb').read()
        photo = base64.b64encode(rf)
        photo = str(photo, encoding='utf-8')
        photos.append(photo)

    return jsonify({"code": 200, "message": "推荐成功", "data": 
        {"recommended_pic": photos, "recommended_text": list(recom_style_names)}})


@app.route('/ImageTransfer', methods=["POST"])
def ImageTransfer():
    json_data = request.json
    content_img = json_data["content_photo"]
    style_img = json_data["style_photo"]
    res = transfer.forward_image(content_img, style_img)
    res = str(res, encoding='utf-8')
    return jsonify({"code": 200, "message": "图像风格迁移成功", "data": {"image_transfer_pic": res}})

@app.route('/TextTransfer', methods=["POST"])
def TextTransfer():
    json_data = request.json
    content_img = json_data["content_photo"]
    style_text = json_data["style_text"]
    res = transfer.forward_text(content_img, style_text)
    res = str(res, encoding='utf-8')
    return jsonify({"code": 200, "message": "文字风格迁移成功", "data": {"text_transfer_pic": res}})

if __name__ == '__main__':
    app.run(host='127.0.1.1', port=22334)
